<template>
  <div class="identity-dialog">
    <el-dialog
      v-model="identityVisible"
      :title="title"
      width="800"
      :model="identityInfo"
      :before-close="cancel"
      draggable
    >
      <el-form style="width: 350px" ref="form" :model="identityInfo" :rules="rules">
        <el-form-item label="商店头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="uploadImages"
            drag
          >
            <img v-if="image" :src="image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商店名称" prop="name">
          <el-input
            v-model="identityInfo.name"
            maxlength="20"
            show-word-limit
            placeholder="请输入商店的名称"
          />
        </el-form-item>
        <el-form-item label="商店描述" prop="description">
          <el-input
            v-model="identityInfo.description"
            maxlength="100"
            show-word-limit
            placeholder="请输入商店描述"
          />
        </el-form-item>
        <el-form-item label="商店标签">
          <div class="add-tags">
            <el-tag
              v-for="tag in identityInfo.tags"
              :key="tag"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="tagVisible"
              ref="tagRef"
              v-model="tag"
              style="max-width: 100px"
              class="w-20"
              size="small"
              maxlength="10"
              show-word-limit
              @keyup.enter="addNewTag"
            />
            <el-button
              v-if="!tagVisible && identityInfo.tags.length < 3"
              class="button-new-tag"
              size="small"
              @click="tagVisible = true"
            >
              + New Tag
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="addNewIdentity" v-if="!props.id">新增</el-button>
          <el-button type="primary" @click="updateIdentityInfo" v-else>修改</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { addIdentity, getIdentityById, updateIdentity } from '@/api/shop'
import { startLoading, stopLoading } from '@/utils/loading'
import { ref, onMounted } from 'vue'

const emit = defineEmits(['close'])

const props = defineProps({
  id: String,
})

// 表单校验
const rules = {
  name: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 1, max: 20, message: '标题字数为1~20字之间', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入商店描述', trigger: 'blur' },
    { min: 1, max: 100, message: '标题字数为1~10字之间', trigger: 'blur' },
  ],
}

// 展示对话框
const identityVisible = ref(true)

const form = ref()

// 展示图片
const image = ref()

// 是否修改过图片
const isChangeImage = ref(false)

// 表单信息
const identityInfo = ref({
  name: '',
  image: '',
  description: '',
  tags: [],
})

// 标签显示
const tagVisible = ref(false)

const tag = ref('')

// 根据id获取商店
const getIdentity = async () => {
  if (!props.id) {
    return
  }
  const { data } = (await getIdentityById(props.id)).data
  identityInfo.value = data
  image.value = data.image
  title.value = data.name
}

const title = ref(props.id ? identityInfo.value.name : '新增商店')

// 修改图片
const uploadImages = (file) => {
  // 判断格式
  const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
  if (!isJPG) {
    ElNotification({
      title: '提示',
      message: '上传图片只能是 JPG、PNG 格式!',
      type: 'warning',
    })
    return false
  }
  // 判断大小
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElNotification({
      title: '提示',
      message: '上传图片大小不能超过2MB',
      type: 'warning',
    })
    return false
  }
  image.value = URL.createObjectURL(file.raw)
  identityInfo.value.image = file.raw
  isChangeImage.value = true
}

// 新增标签
const addNewTag = () => {
  if (tag.value) {
    identityInfo.value.tags.push(tag.value)
    tagVisible.value = false
    tag.value = ''
  }
}

// 删除标签
const handleClose = (tag) => {
  identityInfo.value.tags.splice(identityInfo.value.tags.indexOf(tag), 1)
}

// 新增商店
const addNewIdentity = async () => {
  await form.value.validate()

  const formData = new FormData()
  for (let key in identityInfo.value) {
    formData.append(key, identityInfo.value[key])
  }

  startLoading()
  const data = (await addIdentity(formData)).data
  stopLoading()
  if (data.success) {
    ElNotification({
      title: '提示',
      message: '新增商店成功',
      type: 'success',
    })
    emit('close')
  } else {
    ElNotification({
      title: '提示',
      message: '新增商店失败',
      type: 'error',
    })
  }
}

// 修改商店
const updateIdentityInfo = async () => {
  await form.value.validate()

  const formData = new FormData()
  for (let key in identityInfo.value) {
    if (key === 'image' && isChangeImage.value === false) {
      continue
    }
    // 如果修改过图片，则上传图片
    formData.append(key, identityInfo.value[key])
  }
  const data = (await updateIdentity(formData)).data
  if (data.success) {
    ElNotification({
      title: '提示',
      message: '修改商店成功',
      type: 'success',
    })
    emit('close')
  } else {
    ElNotification({
      title: '提示',
      message: '修改商店失败',
      type: 'error',
    })
  }
}

// 关闭对话框
const cancel = () => {
  emit('close')
}

onMounted(() => {
  getIdentity()
})
</script>

<style scoped less="scss">
.identity-dialog {
  .add-tags {
    display: flex;
    gap: 3px;
  }

  .avatar-uploader {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 178px;
    height: 178px;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
</style>
